﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DepInnerTask.Common.Interface;
using Common.Service;
using System.Collections;
using DepInnerTask.Common.Entity;
using System.IO;
using IBatisNet.DataMapper;
using Common;
using DepInner;
namespace Ultimus.Web
{
    public partial class DepInnerTask : System.Web.UI.Page
    {
        IDepInnerTask task = ServiceContainer.GetService<IDepInnerTask>();
        //IDepInnerTaskReply rep = ServiceContainer.GetService<IDepInnerTaskReply>();
        IUpLoadFile upfile = ServiceContainer.GetService<IUpLoadFile>();
        ITasks tasks = ServiceContainer.GetService<ITasks>();
        ITInBoxRead boxRead = ServiceContainer.GetService<ITInBoxRead>();
        string user = "";//发起人
        string ProcessName = "";//流程名称
        int IncidentNo = 0;//实例编号
        string TaskID = "";//任务编号
        protected void Page_Load(object sender, EventArgs e)
        {
            //int count = 0;
            //IList list = task.GetList("", 0, 10, out count);
           
            ////foreach (TaskEntity entity in list)
            ////{

            ////}
            if (!IsPostBack)
            {
                //获取发起人
                txtFaqi.Text = Request.QueryString["StartUser"];
                if (Request.QueryString["guid"] != "" && Request.QueryString["guid"] != null)
                {
                    hidGuid.Value = Request.QueryString["guid"];// Guid.NewGuid().ToString();//产生GUID唯一标示;
                }
                else {
                    hidGuid.Value = Guid.NewGuid().ToString();//产生GUID唯一标示 ;
                }
                BindFileData();
                if (Request.QueryString["user"] != ""&&Request.QueryString["user"]!=null)
                {
                    user = Request.QueryString["user"];
                }
                if (Request.QueryString["ProcessName"] != ""&&Request.QueryString["ProcessName"] !=null)
                {
                    ProcessName = Request.QueryString["ProcessName"];
                }
                if (Request.QueryString["IncidentNo"] != "" && Request.QueryString["IncidentNo"]!=null)
                {
                    IncidentNo = int.Parse(Request.QueryString["IncidentNo"]);
                }
                if (Request.QueryString["TaskID"] != "" && Request.QueryString["TaskID"] != null)
                {
                    TaskID = Request.QueryString["TaskID"];
                }
            }
        }

        private void BindText()
        { 
        
        }
        /// <summary>
        /// 确定发送部内工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOk_Click(object sender, EventArgs e)
        {
            TInBoxReadEntity Boxentity = new TInBoxReadEntity();
            DepInnerTaskEntity innertask = new DepInnerTaskEntity();
            MessageQueueEntity taskentity = new MessageQueueEntity();
            try
            {
                #region 添加内部工单表
               
                innertask.COPYTO_USERS = txtCopyToUsers.Text.Trim();
                innertask.CREATE_BY =txtFaqi.Text.Trim();
                innertask.CREATE_DATE = DateTime.Now;
                innertask.INCIDENT_NO =IncidentNo;// Convert.ToInt32(Request.QueryString["IncidentNo"]);//实例编号
                innertask.INNER_TASK_ID = hidGuid.Value;
                innertask.INNER_TASK_NO =txtNo.Text.Trim();
                innertask.MESSAGE_CONTENT = txtMess.Text.Trim();
                //if (chkEmail.Checked)//Email
                //{
                //    innertask.MESSAGE_CONTENT = "发送人：" + txtFaqi.Text + "发送时间：" + DateTime.Now + "\n\r发送内容:" + txtMess.Text.Trim();
                //}
                //if (chkMess.Checked)//短信
                //{
                //    innertask.MESSAGE_CONTENT = "发送人：" + txtFaqi.Text + "发送时间：" + DateTime.Now + "要求回复时间：" + txtRepDate.Text + "流程标题：" + txtTitile.Text + "附件：" + file.FileName + "\n\r发送内容:" + txtMess.Text.Trim();
                //}
                if (chkEmail.Checked)
                {
                    innertask.NOTIFY_TYPE = "2";//通知类型（邮件）
                }
                else if (chkMess.Checked)
                {
                    innertask.NOTIFY_TYPE = "1";//通知类型（短信）
                }
                else if (chkMess.Checked && chkEmail.Checked)
                {
                    innertask.NOTIFY_TYPE = "3";//通知类型（都选）
                }
                else
                {
                    innertask.NOTIFY_TYPE = "0";//通知类型(没有选择)
                }
                innertask.PROCESS_NAME = ProcessName;//流程名称
                innertask.REPLY_USERS = txtRepUsers.Text.Trim();
                innertask.REQUIRE_REPLY_DATE = Convert.ToDateTime(txtRepDate.Text.Trim());
                innertask.TASK_DESCRIPTION = txtTaskDes.Text.Trim();
                innertask.TASK_ID = TaskID;//
                innertask.TITLE = txtTitile.Text.Trim();
               
                #endregion

                #region 添加队列消息
                if (chkEmail.Checked||chkMess.Checked)
                {

                    taskentity.BODYS= txtMess.Text.Trim();
                    taskentity.FROMS = txtFaqi.Text.Trim();
                    taskentity.IS_SEND = "1";//1代表是
                    taskentity.MESSAGE_TYPE = innertask.NOTIFY_TYPE;//发送方式
                    taskentity.QUEUE_ID = hidGuid.Value;
                    taskentity.RETRY_TIMES = 1;//发送次数
                    taskentity.SEND_TIME = DateTime.Now;
                    taskentity.SUBJECT = txtTitile.Text.Trim();
                    taskentity.TO_ACCOUNT = txtRepUsers.Text.Trim();//接收人账号(传过来值)
                    taskentity.TO_NAME = txtRepUsers.Text.Trim();
                }
             
                #endregion

                #region 添加待阅表 
                if (txtCopyToUsers.Text != "")
                {
                   
                    Boxentity.INBOX_ID = hidGuid.Value;
                    Boxentity.TASK_TITLE = txtTitile.Text.Trim();
                    Boxentity.TASK_USER = txtFaqi.Text.Trim();
                    Boxentity.ASSIGNEDTO_USER = txtRepUsers.Text.Trim();
                }
                #endregion

                task.Insert(innertask, taskentity, Boxentity);
                MessageBox("派发成功！");
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            { 
            
            }
        }
        #region 封装弹出信息
        private void MessageBox(string name)
        {
            Response.Write("<script type='text/javascript'>alert('" + name + "');</script>");
        }
        #endregion

        protected void gvUpLoadFile_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            
            //如果是绑定数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    ((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除：" + e.Row.Cells[1].Text.Trim() + "吗?')");
                }
            }
        }
        protected void gvUpLoadFile_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
           
            string id = this.gvUpLoadFile.DataKeys[e.RowIndex].Value.ToString();

            //同事删除文件夹中文件
            IList list = upfile.GetList1(id);
            if (list.Count > 0)
            {
                var fileName = ((UpLoadFileEntity)(list[0])).FILE_NAME;
                string pSavedPath1 = Server.MapPath("UpLoad/" + fileName);
                if (File.Exists(pSavedPath1))
                {
                    FileInfo fi = new FileInfo(pSavedPath1);
                    File.Delete(pSavedPath1);
                }
            }
            upfile.Delete(id);
            Response.Redirect(Request.RawUrl);
            
        }
        /// <summary>
        /// 绑定GridView
        /// </summary>
        private void BindFileData()
        {
            IList list = upfile.GetList(hidGuid.Value);
            this.gvUpLoadFile.DataSource = list;
            this.gvUpLoadFile.DataBind();
        }

        /// <summary>
        /// 点击上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //判断是否上传了文件 
            if (file.HasFile)
            {
                //指定上传文件在服务器上的保存路径 
                string savePath = Server.MapPath("UpLoad/");
                //检查服务器上是否存在这个物理路径，如果不存在则创建 
                if (!System.IO.Directory.Exists(savePath))
                {
                    //需要注意的是，需要对这个物理路径有足够的权限，否则会报错 
                    //另外，这个路径应该是在网站之下，而将网站部署在C盘却把上传文件保存在D盘 
                    System.IO.Directory.CreateDirectory(savePath);
                }
                savePath = savePath + "\\" + file.FileName;
                file.SaveAs(savePath);//保存文件 
                //不过需要注意的是，在客户端访问却需要指定的是URL地址，而不是在服务器上的物理地址 
               // literal.Text = string.Format("<a href='upload/{0}'>upload/{0}</a>", file.FileName);
                //插入数据库数据
                UpLoadFileEntity fileEntity = new UpLoadFileEntity();
                fileEntity.FILE_NAME = file.FileName;
                fileEntity.FILE_SAVEPATH = file.FileName;
                fileEntity.GUID = hidGuid.Value;//来源ID
                fileEntity.IS_ACTIVE = "0";//0未激活 1已激活 2失效 
                fileEntity.PROCESS_NAME = Request.QueryString["ProcessName"];
                fileEntity.UPLOAD_BY = txtFaqi.Text.Trim();
                fileEntity.UPLOAD_DATE = DateTime.Now;
                fileEntity.UPLOAD_FILE_ID = Guid.NewGuid().ToString();//主键
                fileEntity.UPLOAD_FILE_TYPE = "";//附件类型
                upfile.Insert(fileEntity);
                BindFileData();
            }
        }

      
    }
}